const { resolve } = require('path')
const Config = require('webpack-chain')
const Webpack = require('webpack')
const chalk = require('chalk')
const WebpackDevServer = require('webpack-dev-server')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const { moduleRules, resolveModules, mapExternals, cliRoot, loadConfig, mergeJmConfig, localIp, root, resolveLoaders, resolveAlias } = require('./util')
const merge = require('lodash/merge')
const defaultDevServer = {
  contentBase: resolve(root, 'dist'),
  port: 8081,
  hot: true,
  host: '0.0.0.0',
  historyApiFallback: true,
  proxy: {
    '/description': {
      target: 'http://localhost:8081',
      pathRewrite: { '/description/plat_des/coms_des': '' },
    }
  }
}

/**
 * 
 * @param { string } configPath
 */
async function serve(configPath) {

  const config = new Config()

  const jmConfig = await loadConfig(configPath)

  mergeConfig(config)

  config.output.path(resolve(root, 'dist'))
  config.resolve.alias.set('debug', resolve(root, 'debug'))

  const webpackJsonConfig = mergeJmConfig(config, jmConfig)

  const devServer = merge({}, defaultDevServer, webpackJsonConfig.devServer || {})

  const compiler = Webpack(webpackJsonConfig)

  // 开启调试
  WebpackDevServer.addDevServerEntrypoints(webpackJsonConfig, devServer)

  const server = new WebpackDevServer(compiler, devServer)

  const port = devServer.port
  const host = devServer.host

  server.listen(port, host, () => {
    console.log(chalk.blue('调试服务已启动'))

    if(host === '0.0.0.0') {
      console.log(chalk.blue(`地址: http://localhost:${port}`))
      console.log(chalk.blue(`局域网地址: http://${localIp}:${port}`))
    } else {
      console.log(chalk.blue(`地址: http://${host}:${port}`))
    }
  })
}

/**
 * 
 * @param { import('webpack-chain') } config 
 */
function mergeConfig(config) {
  config.entry('index').add(resolve(cliRoot, 'src', 'main.js'))

  config.mode('development')

  config.devtool('eval-source-map')

  config.plugin('html').use(HtmlWebpackPlugin, [{
    template: resolve(cliRoot, 'public', 'index.html'),
    filename: 'index.html',
    inject: 'body',
    chunks: ['index']
  }])

  config.plugin('copy').use(CopyWebpackPlugin, [{
    patterns: [{
      from: resolve(cliRoot, 'public', 'static'),
      to: 'static'
    },{
      noErrorOnMissing: true,
      from: resolve(cliRoot, 'node_modules', 'yt-engine', 'dist', 'lib.js'),
      to: 'static/lib.js'
    },{
      noErrorOnMissing: true,
      from: resolve(root, 'node_modules', 'yt-engine', 'dist', 'lib.js'),
      to: 'static/lib.js'
    }]
  }])

  externals(config)

  moduleRules(config)

  resolveModules(config)

  resolveLoaders(config)

  resolveAlias(config)

  return config
}

/**
 * 
 * @param { import("webpack-chain") } config 
 */
function externals(config) {
  config.externals({
    'yt-engine': 'yt_engine'
  })

  return config
}

module.exports = {
  serve
}
